package com.bii.gelapp;

import java.io.ByteArrayOutputStream;

import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;
import org.opencv.android.Utils;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Scalar;
import org.opencv.imgproc.Imgproc;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

public class BrightnessActivity extends Activity {

	private static final int SELECT_PICTURE = 1;
	private static final int ROTATE_PICTURE = 2;

	private static Bitmap resizedbmp;
	private static String picturePath;
	public Bitmap originalBmp; // original image
	public Bitmap activeBmp; // edited image
	Bitmap takenimg; // copy of edited image
	Bitmap brightbmp; // brightness changed image

	Button btImage, btRotate, btSave;
	ImageView ivImage;
	SeekBar sbBrightness;
	TextView tvBrightness;

	// seekbar values
	static int currentprogress;
	static int defaultprogress;
	static int posdifference;

	public Bitmap getActiveBmp() {
		return this.activeBmp;
	}

	// orientation change save state

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Instantiate();
			/*if (savedInstanceState != null) {
				originalBmp = savedInstanceState.getParcelable("originalBmp");
				activeBmp = savedInstanceState.getParcelable("activeBmp");
				currentprogress = savedInstanceState.getInt("currentprogress");
				Instantiate();
				if (activeBmp == null) {
					resizedbmp = Bitmap.createScaledBitmap(activeBmp, 300, 300,
							true);
					ivImage.setImageBitmap(resizedbmp);
				} else {
					resizedbmp = Bitmap.createScaledBitmap(originalBmp, 300,
							300, true);
					ivImage.setImageBitmap(resizedbmp);
				}
				sbBrightness.setProgress(currentprogress);
				btSave.setEnabled(true);
				btRotate.setEnabled(true);
				sbBrightness.setEnabled(true);
			} else {
				Instantiate();
			}*/
		
	}

	/*@Override
	protected void onSaveInstanceState(Bundle outState) {
		// TODO Auto-generated method stub
		super.onSaveInstanceState(outState);
		outState.putParcelable("originalBmp", originalBmp);
		outState.putParcelable("activeBmp", activeBmp);
		outState.putInt("currentprogress", currentprogress);

	}*/

	public void Instantiate() {

		setContentView(R.layout.brightnessactivity);

		// declare buttons, image views, seek bars
		tvBrightness = (TextView) findViewById(R.id.tvBrightness);
		ivImage = (ImageView) findViewById(R.id.ivImage);
		btImage = (Button) findViewById(R.id.btImage);
		btSave = (Button) findViewById(R.id.btSave);
		btRotate = (Button) findViewById(R.id.btRotate);
		sbBrightness = (SeekBar) findViewById(R.id.sbBrightness);
		// don't allow user to click button when no pic is loaded
		btSave.setEnabled(false);
		btRotate.setEnabled(false);
		sbBrightness.setEnabled(false);

		// image selection
		btImage.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent();
				intent.setType("image/*");
				intent.setAction(Intent.ACTION_GET_CONTENT);
				startActivityForResult(
						Intent.createChooser(intent, "Select Picture"),
						SELECT_PICTURE);
			}
		});
		// save button
		btSave.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

			}
		});
		// rotation button
		btRotate.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				Intent goToNextActivity = new Intent(getApplicationContext(),
						RotationActivity.class);
				byte[] bytes = compressImage(activeBmp);
				goToNextActivity.putExtra("BMP", bytes);
				startActivity(goToNextActivity);
			}
		});

		sbBrightness.incrementProgressBy(1);
		sbBrightness.setProgress(50);
		sbBrightness.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
				if (takenimg == null) {
					takenimg = originalBmp;
				}
				currentprogress = sbBrightness.getProgress();
				defaultprogress = 50;
				int difference = currentprogress - defaultprogress;
				int brightness = difference;

				int display = currentprogress - 50;

				brightbmp = doBrightness(takenimg, difference);
				Bitmap resizedbmp = Bitmap.createScaledBitmap(brightbmp, 300,
						300, true);
				ivImage.setImageBitmap(resizedbmp);
				sbBrightness.setProgress(currentprogress);
				tvBrightness.setText("Brightness: " + display);

				activeBmp = brightbmp;

			}
		});

	}

	public static Bitmap doBrightness(Bitmap src, int value) {
		int width = src.getWidth();
		int height = src.getHeight();
		Bitmap bmOut = Bitmap.createBitmap(width, height, src.getConfig());
		int A, R, G, B;
		int pixel;
		for (int x = 0; x < width; ++x) {
			for (int y = 0; y < height; ++y) {
				pixel = src.getPixel(x, y);
				A = Color.alpha(pixel);
				R = Color.red(pixel);
				G = Color.green(pixel);
				B = Color.blue(pixel);
				R += value;
				if (R > 255) {
					R = 255;
				} else if (R < 0) {
					R = 0;
				}

				G += value;
				if (G > 255) {
					G = 255;
				} else if (G < 0) {
					G = 0;
				}

				B += value;
				if (B > 255) {
					B = 255;
				} else if (B < 0) {
					B = 0;
				}
				bmOut.setPixel(x, y, Color.argb(A, R, G, B));
			}

		}
		return bmOut;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == SELECT_PICTURE && resultCode == RESULT_OK
				&& null != data) {

			Uri selectedImage = data.getData();
			String[] filePathColumn = { MediaStore.Images.Media.DATA };

			Cursor cursor = getContentResolver().query(selectedImage,
					filePathColumn, null, null, null);
			cursor.moveToFirst();

			int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
			picturePath = cursor.getString(columnIndex);
			cursor.close();
			originalBmp = BitmapFactory.decodeFile(picturePath);

			/*
			 * originalBmp = Bitmap .createScaledBitmap(originalBmp, 1900,
			 * ((1900 * originalBmp .getHeight()) / originalBmp.getWidth()),
			 * true);
			 */
			if (originalBmp.getWidth() > originalBmp.getHeight()) {
				if (originalBmp.getWidth() > 2000) {
					originalBmp = Bitmap.createScaledBitmap(originalBmp, 2000,
							((2000 * originalBmp.getHeight()) / originalBmp
									.getWidth()), true);
				}
			} else {
				if (originalBmp.getHeight() > 2000) {
					originalBmp = Bitmap.createScaledBitmap(originalBmp, 2000,
							((2000 * originalBmp.getHeight()) / originalBmp
									.getWidth()), true);
				}
			}

			// convert bitmap to matrix
			Mat srcImg = new Mat(originalBmp.getHeight(),
					originalBmp.getWidth(), CvType.CV_8U, new Scalar(4));
			Bitmap myBitmap32 = originalBmp.copy(Bitmap.Config.ARGB_8888, true);
			Utils.bitmapToMat(myBitmap32, srcImg);

			// convert to grayscale
			Mat grayImg = new Mat();
			Imgproc.cvtColor(srcImg, grayImg, Imgproc.COLOR_BGR2GRAY);
			originalBmp = Bitmap.createBitmap(grayImg.cols(), grayImg.rows(),
					Bitmap.Config.RGB_565);

			// convert mat back to bitmap set originalBmp
			Utils.matToBitmap(grayImg, originalBmp);
			// set activeBmp
			activeBmp = originalBmp.copy(Bitmap.Config.RGB_565, true);
			// activeBmp = originalBmp;
			// resized bitmap to fit image view
			resizedbmp = Bitmap.createScaledBitmap(activeBmp, 300, 300, true);
			ivImage.setImageBitmap(resizedbmp);
			sbBrightness.setProgress(50);
			// allow users to click buttons
			btSave.setEnabled(true);
			btRotate.setEnabled(true);
			sbBrightness.setEnabled(true);
		}
	}

	public byte[] compressImage(Bitmap image) {
		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		image.compress(Bitmap.CompressFormat.PNG, 0, stream);
		byte[] bytes = stream.toByteArray();
		return bytes;

	}

	// this is for opencv
	public BaseLoaderCallback mOpenCVCallBack = new BaseLoaderCallback(this) {
		@Override
		public void onManagerConnected(int status) {
			switch (status) {
			case LoaderCallbackInterface.SUCCESS:
				// DO YOUR WORK/STUFF HERE
				break;
			default:
				super.onManagerConnected(status);
				break;
			}
		}
	};

	// onresume is for the opencv
	@Override
	protected void onResume() {
		super.onResume();
		OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_8, this,
				mOpenCVCallBack);
	}

	

}
